package com.ncmmall.mall.controller.business.goods;

import com.ncmmall.application.business.goods.GoodsApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.attribute.GoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttribute;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.goods.image.GoodsImage;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * @Description: 商品管理
 * @Date: 2019-07-10 17:44
 */
@Controller
@RequestMapping(value = "/mall/goods/")
public class SaleGoodsController {

    private final static Logger logger = LoggerFactory.getLogger(SaleGoodsController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsApplication goodsApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 在售商品列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, Goods goods) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select u from Goods u where u.isSupplier=0 ", params, goods);
        QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Goods.class);
        List<WebUser> merchants = queryChannelService.findAll(QWebUser.webUser.role.name.eq("MERCHANT"), WebUser.class);

        List<GoodsChannel> channels = queryChannelService.findAll("select c from GoodsChannel c where c.deleteStatus = 0 and  c.level = 1 and c.status = 1 ", GoodsChannel.class);

        model.addAttribute("page", page).addAttribute("params", goods).addAttribute("merchants", merchants).addAttribute("channels", channels);

        return "mall/goods/list";
    }

    /**
     * 编辑商品信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        List<GoodsChannel> channels = queryChannelService.findAll(QGoodsChannel.goodsChannel.id.isNotNull(), GoodsChannel.class);

        StringBuilder imagesData = new StringBuilder();
        for (GoodsImage image : goods.getImages()) {
            imagesData.append(image.getName());
            imagesData.append(";");
        }

        goods.setImagesData(imagesData.toString());

        List<GoodsAttribute> attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(Securitys.currentUser().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()), GoodsAttribute.class);

        model.addAttribute("_method", "PUT").addAttribute("goods", goods).addAttribute("channels", channels).addAttribute("attributes", attributes);

        return "mall/goods/form";

    }

    /**
     * 编辑商品信息
     *
     * @param requestWith
     * @param goods
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Goods goods) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            goodsApplication.modify(goods);
            logApplication.eventOfSystem(Securitys.currentUser(), "修改商品信息" + goods.getName(), Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            logger.error("[编辑商品信息异常]", e);
            return ImmutableMap.of("status", false, "message", e.getMessage());
        }
    }

    /**
     * 查看详情
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        List<GoodsAttribute> attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.merchant.id.eq(goods.getMerchant().getId()).and(QGoodsAttribute.goodsAttribute.parent.isNull()), GoodsAttribute.class);

        model.addAttribute("goods", goods).addAttribute("attributes", attributes);

        return "mall/goods/detail";
    }

    /**
     * 批量推荐
     *
     * @param request
     * @param requestWith
     * @param data
     * @return
     */
    @RequestMapping(value = "/allRecommend", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> allRecommend(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            goodsApplication.allRecommend(Lists.transform(ids, new Function<String, Goods>() {
                @Nullable
                @Override
                public Goods apply(@Nullable String input) {
                    Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(Longs.tryParse(input)), Goods.class);
                    return goods;
                }
            }));

            logApplication.eventOfSystem(Securitys.currentUser(), "批量推荐商品到首页", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[批量审核通过商品异常]", e);
            return ImmutableMap.of("status", false);

        }
    }


    @RequestMapping(value = "/allUnRecommend", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> allUnRecommend(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            goodsApplication.allUnRecommend(Lists.transform(ids, new Function<String, Goods>() {
                @Nullable
                @Override
                public Goods apply(@Nullable String input) {
                    Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(Longs.tryParse(input)), Goods.class);
                    return goods;
                }
            }));

            logApplication.eventOfSystem(Securitys.currentUser(), "批量取消推荐商品到首页", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[批量审核通过商品异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 推荐商品到首页
     *
     * @param requestWith
     * @param goods
     * @return
     */
    @RequestMapping(value = "/recommend", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> recommend(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Goods goods) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            goodsApplication.recommend(goods);
            logApplication.eventOfSystem(Securitys.currentUser(), "推荐商品" + goods.getName(), Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[审核商品异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Goods goods) {

        if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getId() > 0) {
            goods.setGoodsChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getId() > 0) {
            goods.getGoodsChannel().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getParent().getId() > 0) {
            goods.getGoodsChannel().getParent().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getParent().getId());
        }

        if (goods.getMerchant() != null && goods.getMerchant().getId() > 0) {
            sql += " and u.merchant.id = :merchantId ";
            params.put("merchantId", goods.getMerchant().getId());
        }

        if (goods.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", goods.getStatus());
        } else {
            sql += " and u.status in (3,6) ";
        }

        if (!Strings.isNullOrEmpty(goods.getGoodsNo())) {
            sql += " and u.goodsNo like :goodsno ";
            params.put("goodsno", "%" + goods.getGoodsNo() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + goods.getName() + "%");
        }


        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByPrice())) {
            sql += " order by u.defaultPrice " + goods.getOrderByPrice();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByStore())) {
            sql += " order by u.store " + goods.getOrderByStore();
        } else if (!Strings.isNullOrEmpty(goods.getOrderBySalesVolume())) {
            sql += " order by u.salesVolume " + goods.getOrderBySalesVolume();
        } else {
            sql += " order by u.createTime desc ";
        }

        return sql;
    }


    /**
     * 选择商品页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/choose", method = RequestMethod.GET)
    public String choose(HttpServletRequest request, Model model, PageParams pageParams, Goods goods) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select u from Goods u where u.isSupplier=0  ", params, goods);
        QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Goods.class);
        List<WebUser> merchants = queryChannelService.findAll(QWebUser.webUser.role.name.eq("MERCHANT"), WebUser.class);

        model.addAttribute("page", page).addAttribute("params", goods).addAttribute("merchants", merchants);

        return "mall/goods/choose";
    }

    /**
     * 获取二、三级商品类目
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/childChannels", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> middleChannels(@RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Map<String, Object> data = Maps.newHashMap();
            data.put("result", queryChannelService.findAll(QGoodsChannel.goodsChannel.parent.id.eq(id).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0)), GoodsChannel.class));
            data.put("status", true);

            return data;

        } catch (Exception e) {
            logger.error("[查询二级分类异常:]", e);
            return ImmutableMap.of("status", false);
        }
    }


}
